# pip install python-docx
from docx import Document
import random
import requests
import time
import datetime
import urllib.parse
import json
# pip install Interval
from interval import Interval

meizi_headers = [
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36",
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14",
    "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)",
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
    'Opera/9.25 (Windows NT 5.1; U; en)',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
    'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
    'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
    "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7",
    "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0",
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'
]
# 给请求指定一个请求头来模拟chrome浏览器
global headers
headers = {'User-Agent': random.choice(meizi_headers)}

# yyyy-mm-dd 开始时间
startDate = "2021-12-15"
# 结束时间
endDate = "2022-01-15"
# 上班时间
up_time = '09:00'
# 下班时间
down_time = '18:00'
# 打卡误差点(单位:分)
interval = 15
# 姓名
name = '陈泽恩'
# 部门
dept_name = '数字城市事业本部'
# 备注
remark = '石家庄'


def main():
    # 工作日变量
    workDay = []
    #调用百度日历接口获取工作日
    workDay = baidu_url(workDay)
    # workDay获取工作日  但是是前后三个月左右的   下边筛选一下
    workDay = search_workday(workDay)

    # 随机上下班时间
    time_obj = random_time(len(workDay))



    # 将工作日写入word
    document = Document('work.docx')  # 打开文件demo.docx
    # 读取第1个表格
    tb1 = document.tables[0]
    for i in range(0,len(workDay)):
        # 获取第一个表格的行的单元格
        row_cells = tb1.rows[i+2].cells
        row_cells[1].text = workDay[i]
        row_cells[2].text = name
        row_cells[3].text = dept_name
        row_cells[4].text = time_obj[i].up
        row_cells[5].text = time_obj[i].down
        row_cells[6].text = remark

    document.save("work1.docx");


def baidu_url(workDay):
    url = "https://sp1.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?tn=wisetpl&format=json&resource_id=39043"
    timeArray = time.strptime(startDate, "%Y-%m-%d")
    otherStyleTime = time.strftime("%Y{y}%m{m}", timeArray).format(y='年', m='月', d='日')
    url += "&query=" + urllib.parse.quote(otherStyleTime)
    # 请求百度的日历接口
    res = requests.get(url, headers=headers)
    result = json.loads(res.text)
    if result['status'] == '0':
        data_arr = result['data']
        almanac_arr = data_arr[0]['almanac']
        for almanac in almanac_arr:
            day = str(almanac['year']) + str(format_month(almanac['month'])) + str(almanac['day'])
            if '六' == str(almanac['cnDay']) or '日' == str(almanac['cnDay']):
                if 'status' in almanac and '2' == str(almanac['status']):
                    workDay.append(day)
            if '一' == str(almanac['cnDay']) or '二' == str(almanac['cnDay']) or '三' == str(
                    almanac['cnDay']) or '四' == str(almanac['cnDay']) or '五' == str(almanac['cnDay']):
                if 'status' in almanac and '1' == str(almanac['status']):
                    continue
                else:
                    workDay.append(day)
    else:
        print('调用百度日历接口失败,放弃使用吧,赶紧的,毁灭吧!')
    return workDay


# 将 workDay 里的日期  筛选出来   在startDate和endDate之间
def search_workday(workDay):
    temp_work_day = []
    start_time = time.strptime(startDate, "%Y-%m-%d")
    end_time = time.strptime(endDate, "%Y-%m-%d")
    for day in workDay:
        day_time = time.strptime(day, "%Y%m%d")
        time_interval = Interval(start_time, end_time)
        if day_time in time_interval:
            temp_work_day.append(time.strftime("%Y{y}%m{m}%d{d}", day_time).format(y='年', m='月', d='日'))
    return temp_work_day


# 因为python转换日期中  %m	表示月，数字01-12  所以当月份为1的时候  必须转为01 否则 2022112 本来是2022-1-12 就转换为2022-11-2
def format_month(month):
    if int(month) < 10:
        return '0'+month
    else:
        return month


# 随机生成上下班点
# 生成的上班点  =  上班点-随机数(0到interval)
# 生成的下班点  =  下班点+随机数(0到interval)
def random_time(work_num):
    # 注意 这里利用的是 datetime  而非是 time
    # datetime.datetime.strptime 将字符串转成datetime的时间
    up_date = datetime.datetime.strptime(up_time, "%H:%M")
    down_date = datetime.datetime.strptime(down_time, "%H:%M")

    temp = []
    for i in range(0, work_num):
        minu = random.randint(0,interval)
        # datetime.timedelta(minutes=minu) 变化N分钟
        # strftime  datetime的时间转成字符串
        new_up_date = (up_date - datetime.timedelta(minutes=minu)).strftime('%H:%M')
        minu_1 = random.randint(0, interval)
        new_down_date = (down_date + datetime.timedelta(minutes=minu_1)).strftime('%H:%M')
        obj = Timeobj(new_up_date, new_down_date)
        temp.append(obj)
    return temp


class Timeobj:
    def __init__(self, up, down):
        self.up = up
        self.down = down


if __name__ == '__main__':
    main()